#include "Engine.h"

namespace TSS
{

	Input::Input(HWND window)
	{
		hWnd = window;

		DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&di, NULL);

		//setup keyboard
		di->CreateDevice(GUID_SysKeyboard, &keyboard, NULL);
		keyboard->SetDataFormat(&c_dfDIKeyboard);
		keyboard->SetCooperativeLevel(hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
		keyboard->Acquire();

		//clear keys
		memset(keyState, 0, 256);

		//setup mouse
		di->CreateDevice(GUID_SysMouse, &mouse, NULL);
		mouse->SetDataFormat(&c_dfDIMouse);
		mouse->SetCooperativeLevel(hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
		mouse->Acquire();
	}

	Input::~Input()
	{
		di->Release();
		keyboard->Release();
		mouse->Release();
	}

	void Input::Update()
	{
		keyboard->Poll();
		if(!SUCCEEDED(keyboard->GetDeviceState(256, (LPVOID)&keyState)))
		{
			//keyboard device lost, try to get it back
			keyboard->Acquire();
		}

		mouse->Poll();
		if(!SUCCEEDED(mouse->GetDeviceState(sizeof(DIMOUSESTATE), &mouseState)))
		{
			//mouse lost try to get it back
			mouse->Acquire();
		}

		GetCursorPos(&position);
		ScreenToClient(hWnd, &position);
	}

	int Input::GetMouseButton(char button)
	{
		return (mouseState.rgbButtons[button] & 0x80);
	}
};